using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SoftwarePlusServices.ReferenceBits.OutlookPlusServices;
using Microsoft.Office.Interop.Outlook;


namespace Microsoft.SoftwarePlusServices.ReferenceBits.OutlookPlusServices._ScheduledTasks
{
    class GetTaskList : Scheduler
    {


        public GetTaskList()
            : base()
        {
            
			// TODO Write code to do any initialization necessary for GetTaskList
            
        }

        public override void PerformUpdate()
        {
            // patrickyong step 10
			// TODO Write code here to handle the timer for GetTaskList

            PostItem postItem; 

            Folders.IssueTrackerClass folder = new Folders.IssueTrackerClass(Implementation.RootFolder);

            if (folder != null)
            {
                IssueTrackerService.IssueTrackerServiceClient proxy = new IssueTrackerService.IssueTrackerServiceClient();

                try
                {
                    proxy.Open();

                    List<IssueTrackerService.Issue> issues = proxy.TaskList("", "");

                    foreach (var issue in issues)
                    {
                        postItem = folder.FindItem(issue.Id.ToString());

                        if (postItem == null)
                            folder.CreateItem(issue);
                        else
                        {
                            if (postItem.UserProperties["Workflow State"].Value.ToString() != issue.CurrentStateName) 
                                folder.UpdateItem(issue, postItem);
                        }
                    }

                }
                catch (System.Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    if (proxy.State == System.ServiceModel.CommunicationState.Opened)
                        proxy.Close();
                }
            }
        }
    }
}
